//
//  NGSecondViewController.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 1/8/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "NGTestLogViewController.h"
#import "NGDataRetrievingService.h"
#import "SetLocationRequest.h"
#import "SetLocationResponse.h"
#import "SetLocationsResponse.h"
#import "LoginRequest.h"
#import "LoginHandler.h"
#import "WebServiceCaller.h"
#import "NSDate+Extensions.h"
#import "NGUtility.h"
#import "SetLocationsRequest.h"
#import "NGDeviceData.h"
#import "NGDBHelper.h"
#import "SharedPrefs.h"

@implementation NGTestLogViewController

@synthesize testSetLocationResultText;

- (void)run:(NGLocation *) location {
    NGDataRetrievingService* service = [NGDataRetrievingService service];
	service.logging = YES;
	
	[service setLocation:self 
				  action: @selector(setLocationHandler:)
			  deviceCode: location.deviceCode
		  lastLocation_X: location.lat 
		  lastLocation_Y: location.lon 
			   tarihSaat: location.tarihSaat 
				   speed: location.speed 
				  status: location.status 
			  nameValues: [NSMutableArray array]];
    
	NSLog(@"setLocation test çalıştırıldı.");
}


#pragma mark - setLocation(s) handler

- (void) setLocationHandler: (id) value {
    
    SetLocationResponse *response = [SetLocationResponse alloc];
    response.test = TRUE;
    NSString *dateStr = [[NSDate date] toFormattedString];
	if([value isKindOfClass:[NSError class]]) {
		NSLog(@"TEST-->NSERROR.....%@", value);
        response = [response initWithError:value];
	} else if([value isKindOfClass:[SoapFault class]]) {
		NSLog(@"TEST-->SOAP FAULT.....%@", value);
        response = [response initWithSoapFault:value];
	} else {
        NSLog(@"TEST-->setLocation returned the value:\n%@\n%@\n", dateStr, (NSString *) value);
        response = [response initWithResponseXml:(NSString*)value];
    }
    if (![response isSuccessful]) {
        //TODO veri tabanına kaydedilmesi gerekir
        if ([response needRelogin]) {
            LoginRequest *loginRequest = [[[LoginRequest alloc] init] autorelease];
            loginRequest.userName = [SharedPrefs getUserName];
            loginRequest.password = [SharedPrefs getPassword];
            LoginHandler *handler = [[[LoginHandler alloc] init:loginRequest] autorelease];
            [WebServisCaller callWebServiceLogin:loginRequest target:handler];
        }
        NSLog(@"%@", response);
    } else {
        //insert messages to db if any exists
        NGDBHelper *db = [NGDBHelper openDatabase];
        [db insertMessages:[response getMessages]];
        [response processCommands];
    }
    NSString *desc = [response description];
    NSLog(@"%@", desc);
    [testSetLocationResultText setText:desc];
    [self hideActivityView];
}

- (void) setLocationsHandler: (id) value {
    
    SetLocationsResponse *response = [SetLocationsResponse alloc];
    NSString *dateStr = [[NSDate date] toFormattedString];
	if([value isKindOfClass:[NSError class]]) {
		NSLog(@"TEST-->NSERROR.....%@", value);
        response = [response initWithError:value];
	} else if([value isKindOfClass:[SoapFault class]]) {
		NSLog(@"TEST-->SOAP FAULT.....%@", value);
        response = [response initWithSoapFault:value];
	} else {
        NSLog(@"TEST-->setLocations returned the value:\n%@\n%@\n", dateStr, (NSString *) value);
        response = [response initWithResponseXml:(NSString*)value];
    }
    if (![response isSuccessful]) {
        //setLocations zaten konumlar gönderilemediği zaman çağrılmalıdır.
        //Böyle bir durum olmaması gerekir !!
        
    } else {
        //insert messages to db if any exists
        NGDBHelper *db = [NGDBHelper openDatabase];
        [db insertMessages:[response getMessages]];
        [response processCommands];
    }
    [testSetLocationResultText setText:[response description]];
    [self hideActivityView];

}

- (IBAction)testSetLocationxx:(id)sender {
    [testSetLocationResultText setText:[[SetLocationResponse test] description]];
}

#pragma mark - button actions

- (IBAction)testSetLocation:(id)sender {
	
    [self showActivityView];
    
	NGLocation *location = [NGLocation alloc];
	location.lat = 39.91378465;
	location.lon = 32.85948565;
	location.speed = @"0.534";
	location.status = DURDU;
	location.tarihSaat = [NSDate date];
	location.deviceCode = [NGUtility getDeviceId];
    
    SetLocationRequest *request = [[SetLocationRequest alloc] initWithLocation:location];
    
    [WebServisCaller callWebService:request target:self];
    
}

- (IBAction)testSetLocations:(id)sender {
	
    [self showActivityView];
    
	NGLocation *location1 = [NGLocation alloc];
	location1.lat = 39.91378465;
	location1.lon = 32.85948565;
	location1.speed = @"0.534";
	location1.status = DURDU;
	location1.tarihSaat = [NSDate date];
	location1.deviceCode = [NGUtility getDeviceId];
    
	NGLocation *location2 = [NGLocation alloc];
	location2.lat = 40.90078464;
	location2.lon = 33.8596765;
	location2.speed = @"1.666";
	location2.status = UYGULAMA_ACILDI;
	location2.tarihSaat = [NSDate date];
	location2.deviceCode = [NGUtility getDeviceId];
    
    NGLocation *location3 = [NGLocation alloc];
	location3.lat = 41.90078464;
	location3.lon = 35.8596765;
	location3.speed = @"2.666";
	location3.status = HAREKET_EDIYOR;
	location3.tarihSaat = [NSDate date];
	location3.deviceCode = [NGUtility getDeviceId];
    
    /*
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[[NGDeviceData alloc] initWithNGLocation:location1],
                             [[NGDeviceData alloc] initWithNGLocation:location2], nil];
    
     */
    NSMutableArray *array  = [[NSMutableArray alloc] initWithCapacity:3];
    [array addObject:[[NGDeviceData alloc] initWithNGLocation:location1]];
    [array addObject:[[NGDeviceData alloc] initWithNGLocation:location2]];
    [array addObject:[[NGDeviceData alloc] initWithNGLocation:location3]];

    SetLocationsRequest *request = [[SetLocationsRequest alloc] initWithLocations:array];
    
    [WebServisCaller callWebServiceSetLocations:request  target:self];
    
}

-(IBAction)cancel:(id)sender {
    [self.view removeFromSuperview];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        nibNameOrNil = [nibNameOrNil stringByAppendingString:@"-ipad"];
    }
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"second"];
    }
    return self;
}
							
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end
